<?php
namespace app\demo\controller;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;

class Excel
{
    // 导出Excel
    private function index()
    {
        $list = [
            "春江潮水连海平，",
            "海上明月共潮生。",
            "滟滟随波千万里，",
            "何处春江无月明！",
            "江流宛转绕芳甸，",
            "月照花林皆似霰；",
            "空里流霜不觉飞，",
            "汀上白沙看不见。",
            "江天一色无纤尘，",
            "皎皎空中孤月轮。",
            "江畔何人初见月？",
            "江月何年初照人？",
            "人生代代无穷已，",
            "江月年年只相似。",
            "不知江月待何人，",
            "但见长江送流水。"
        ];

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $title = '年收费统计表';
        $sheet->setTitle($title);
        $sheet->setCellValue('A1', 'ID');
        $sheet->setCellValue('B1', '句子');
        $sheet->getColumnDimension('A')->setWidth(12);
        $sheet->getColumnDimension('B')->setWidth(20);

        $index = 2;
        foreach ($list as $key=>$row) {
            $sheet->setCellValue('A'.$index, $key+1);
            $sheet->setCellValueExplicit('B'.$index, $row,DataType::TYPE_STRING);
            $index++;
        }
        $writer = new Xlsx($spreadsheet);
        $filename = date('YmdHis') . '.xlsx';

        $download = true;

        if($download) {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出07Excel文件
            header('Content-Disposition: attachment;filename=' . $filename);//告诉浏览器输出浏览器名称
            header('Cache-Control: max-age=0');//禁止缓存
            $writer->save('php://output'); // 直接下载
        }else {
            $writer->save($filename); // 保存到文件
            exit('success');
        }
//        pp($list);
    }

}
